<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>动态代理与静态代理 | Eetal&#39;s Blog</title>

  <!-- keywords -->
  

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="欢迎查看Eetal的第十七篇博客–动态代理与静态代理 静态代理—硬编码没啥好说的，就是像装饰模式一样 123456789101112131415161718192021public class StaticProxy extends Object&amp;#123;		Object object;		public StaticProxy(Object object) &amp;#123;		this.object">
<meta property="og:type" content="article">
<meta property="og:title" content="动态代理与静态代理">
<meta property="og:url" content="http://eetal.gitee.io/blog/2019/04/07/动态代理与静态代理/index.html">
<meta property="og:site_name" content="Eetal&#39;s Blog">
<meta property="og:description" content="欢迎查看Eetal的第十七篇博客–动态代理与静态代理 静态代理—硬编码没啥好说的，就是像装饰模式一样 123456789101112131415161718192021public class StaticProxy extends Object&amp;#123;		Object object;		public StaticProxy(Object object) &amp;#123;		this.object">
<meta property="og:locale" content="default">
<meta property="og:updated_time" content="2019-04-08T02:16:37.510Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="动态代理与静态代理">
<meta name="twitter:description" content="欢迎查看Eetal的第十七篇博客–动态代理与静态代理 静态代理—硬编码没啥好说的，就是像装饰模式一样 123456789101112131415161718192021public class StaticProxy extends Object&amp;#123;		Object object;		public StaticProxy(Object object) &amp;#123;		this.object">
  
    <link rel="alternative" href="/atom.xml" title="Eetal&#39;s Blog" type="application/atom+xml">
  
  
    <link rel="icon" href="http://www.yangyitao.top/FiveChess/resource/ico/favicon.ico">
  
  <link rel="stylesheet" href="/blog/css/style.css">
  
  

  <script src="//cdn.bootcss.com/require.js/2.3.2/require.min.js"></script>
  <script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>

  
</head>
<body>
  <div id="container">
    <div id="particles-js"></div>
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
	<header id="header" class="inner">
		<a href="/" class="profilepic">
			
			<img lazy-src="/blog/images/head.jpg" class="js-avatar">
			
		</a>

		<hgroup>
		  <h1 class="header-author"><a href="/">Eetal</a></h1>
		</hgroup>

		
		<p class="header-subtitle">java coder</p>
		

		
			<div class="switch-btn">
				<div class="icon">
					<div class="icon-ctn">
						<div class="icon-wrap icon-house" data-idx="0">
							<div class="birdhouse"></div>
							<div class="birdhouse_holes"></div>
						</div>
						<div class="icon-wrap icon-ribbon hide" data-idx="1">
							<div class="ribbon"></div>
						</div>
						
						<div class="icon-wrap icon-link hide" data-idx="2">
							<div class="loopback_l"></div>
							<div class="loopback_r"></div>
						</div>
						
						
					</div>
					
				</div>
				<div class="tips-box hide">
					<div class="tips-arrow"></div>
					<ul class="tips-inner">
						<li>菜单</li>
						<li>标签</li>
						
						<li>友情链接</li>
						
						
					</ul>
				</div>
			</div>
		

		<div class="switch-area">
			<div class="switch-wrap">
				<section class="switch-part switch-part1">
					<nav class="header-menu">
						<ul>
						
							<li><a href="/blog/">Home</a></li>
				        
							<li><a href="/blog/archives">Archives</a></li>
				        
						</ul>
					</nav>
					<nav class="header-nav">
						<div class="social">
							
						</div>
					</nav>
				</section>
				
				
				<section class="switch-part switch-part2">
					<div class="widget tagcloud" id="js-tagcloud">
						
					</div>
				</section>
				
				
				
				<section class="switch-part switch-part3">
					<div id="js-friends">
					
			          <a target="_blank" class="main-nav-link switch-friends-link" href="https://github.com/smackgg/hexo-theme-smackdown">smackdown</a>
			        
			        </div>
				</section>
				

				
			</div>
		</div>
	</header>				
</div>
    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
  	<div class="overlay">
  		<div class="slider-trigger"></div>
  		<h1 class="header-author js-mobile-header hide">Eetal</h1>
  	</div>
	<div class="intrude-less">
		<header id="header" class="inner">
			<div class="profilepic">
				<img lazy-src="/blog/images/head.jpg" class="js-avatar">
			</div>
			<hgroup>
			  <h1 class="header-author">Eetal</h1>
			</hgroup>
			
			<p class="header-subtitle">java coder</p>
			
			<nav class="header-menu">
				<ul>
				
					<li><a href="/blog/">Home</a></li>
		        
					<li><a href="/blog/archives">Archives</a></li>
		        
		        <div class="clearfix"></div>
				</ul>
			</nav>
			<nav class="header-nav">
				<div class="social">
					
				</div>
			</nav>
		</header>				
	</div>
</nav>
      <div class="body-wrap"><article id="post-动态代理与静态代理" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="/blog/2019/04/07/动态代理与静态代理/" class="article-date">
  	<time datetime="2019-04-07T15:41:21.467Z" itemprop="datePublished">2019-04-07</time>
</a>
    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      动态代理与静态代理
      
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        
        

        
        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>欢迎查看Eetal的第十七篇博客–动态代理与静态代理</p>
<h2 id="静态代理—硬编码"><a href="#静态代理—硬编码" class="headerlink" title="静态代理—硬编码"></a>静态代理—硬编码</h2><p>没啥好说的，就是像装饰模式一样</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">public class StaticProxy extends Object&#123;</span><br><span class="line">	</span><br><span class="line">	Object object;</span><br><span class="line">	</span><br><span class="line">	public StaticProxy(Object object) &#123;</span><br><span class="line">		this.object = object;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	@Override</span><br><span class="line">	public int <span class="function"><span class="title">hashCode</span></span>() &#123;</span><br><span class="line">		System.out.println(<span class="string">"proxy decorate start..."</span>);</span><br><span class="line">		int hashCode = object.hashCode();</span><br><span class="line">		System.out.println(<span class="string">"proxy decorate end..."</span>);</span><br><span class="line">		<span class="built_in">return</span> hashCode;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	public static void main(String[] args) &#123;</span><br><span class="line">		Object proxy = new StaticProxy(new Object());</span><br><span class="line">		System.out.println(proxy.hashCode());</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="动态代理"><a href="#动态代理" class="headerlink" title="动态代理"></a>动态代理</h2><h3 id="JDK动态代理—反射、Proxy、InvocationHandler"><a href="#JDK动态代理—反射、Proxy、InvocationHandler" class="headerlink" title="JDK动态代理—反射、Proxy、InvocationHandler"></a>JDK动态代理—反射、Proxy、InvocationHandler</h3><p>jdk动态代理要求对象必须实现接口<br>并且仅会代理接口方法以及equals，hashCode和toString三个Object类的方法<br>生成的代理类也仅是实现这些接口和继承Proxy所以接口里没有的方法在代理对象里不存在<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line">public class DynamicProxy &#123;</span><br><span class="line">	static class BAInvocationHandler implements InvocationHandler&#123;</span><br><span class="line">		</span><br><span class="line">		private Object realObj;</span><br><span class="line">		</span><br><span class="line">		public BAInvocationHandler(Object realObj) &#123;</span><br><span class="line">			this.realObj = realObj;</span><br><span class="line">		&#125;</span><br><span class="line">		</span><br><span class="line">		public void <span class="function"><span class="title">doBefore</span></span>() &#123;</span><br><span class="line">			System.out.println(<span class="string">"before ..."</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		</span><br><span class="line">		public void <span class="function"><span class="title">doAfter</span></span>() &#123;</span><br><span class="line">			System.out.println(<span class="string">"after ..."</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		</span><br><span class="line">		@Override</span><br><span class="line">		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable &#123;</span><br><span class="line">			//proxy为代理对象，所以此处不能调用proxy的方法否则会栈溢出死锁</span><br><span class="line">			//proxy是在newProxyInstance时生成并在调用时传进来的，因为invocationHandler与Proxy是聚合模式</span><br><span class="line">			//所以在invocation中获取不到代理对象，只能通过这种方式传递进来</span><br><span class="line">			doBefore();</span><br><span class="line">			Object result = method.invoke(realObj, args);</span><br><span class="line">			System.out.println(<span class="string">"invoke result :"</span>+result);</span><br><span class="line">			doAfter();</span><br><span class="line">			<span class="built_in">return</span> result;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line">	static &lt;T&gt;T getInstance(Object realObj,Class&lt;T&gt;... clazz) &#123;</span><br><span class="line">		//第一个T泛型方法</span><br><span class="line">		//clazz 该代理类实现的接口</span><br><span class="line">		<span class="built_in">return</span> (T)Proxy.newProxyInstance(clazz[0].getClassLoader(), clazz,new BAInvocationHandler(realObj));</span><br><span class="line">	&#125;</span><br><span class="line">	public static void main(String[] args) &#123;</span><br><span class="line">		Object o = getInstance(new Object(),Serializable.class);</span><br><span class="line">		o.hashCode();</span><br><span class="line">		System.out.println(o instanceof Proxy);</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>由于jdk动态代理基于接口的特性，使得其只能代理接口对象的方法，也就是必须实现接口<br>至于为什么，我个人的理解是在运行时<br>1.其要继承Proxy，因为Proxy封装了动态代理的底层实现，所以Proxy不能是接口，因此只能通过继承来组合（通过聚合或者组合还是离不开要修改字节码）<br>2.jdk反射只能得到每一个class，interface等的field的名称，返回值类型，形参类型，方法体是得不到的，<br>否则就得通过读取修改字节码来生成新的class的字节码文件(cglib就是这么做的)，而读取解析修改字节码效率肯定低一点<br>因此jdk代理只代理接口对象，实际需要一个原对象，再生成一个代理对象，使用的是代理对象<br>注意是对象因为原对象一些在接口中不存在的属性在代理对象中是不存在的，这也是需要getter、setter存在的一个原因</p>
<h3 id="CGLIB动态代理—修改字节码，生成新的子类Class"><a href="#CGLIB动态代理—修改字节码，生成新的子类Class" class="headerlink" title="CGLIB动态代理—修改字节码，生成新的子类Class"></a>CGLIB动态代理—修改字节码，生成新的子类Class</h3><p>当面对特殊的场景，比如就是没有实现任何接口，或者希望获取到所有属性，得到一个子类型的类型，就需要通过cglib了<br>cglib的做法是，通过读取修改字节码，创建一个继承了原有class的子类，所以cglib是代理类，代理方法，而不是代理对象<br>cglib会代理方法中所有不是final类型的非静态方法方法（因为静态方法不会使用代理对象和代理类）<br>使用时是直接使用代理类去创建对象，只有一个对象，因此效率较jdk代理低一点<br>在spring中就是根据要代理的类是否有实现接口，而决定使用cglib还是jdk动态代理<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line">public class CGLIBDynamicProxy &#123;</span><br><span class="line">	static class Test&#123;</span><br><span class="line">		public final void <span class="function"><span class="title">finalMethod</span></span>() &#123;</span><br><span class="line">			System.out.println(<span class="string">"final"</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		public void <span class="function"><span class="title">method</span></span>() &#123;</span><br><span class="line">			System.out.println(<span class="string">"method"</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		public static void <span class="function"><span class="title">staticMethod</span></span>()&#123;</span><br><span class="line">			System.out.println(<span class="string">"staticMethod..."</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	static class BAInterceptor implements MethodInterceptor&#123;</span><br><span class="line">		</span><br><span class="line">		public void <span class="function"><span class="title">doBefore</span></span>() &#123;</span><br><span class="line">			System.out.println(<span class="string">"\nbefore ..."</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		</span><br><span class="line">		public void <span class="function"><span class="title">doAfter</span></span>() &#123;</span><br><span class="line">			System.out.println(<span class="string">"after ...\n"</span>);</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		@Override</span><br><span class="line">		public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable &#123;</span><br><span class="line">			//proxy---代理类对象</span><br><span class="line">			//method---代理后的方法</span><br><span class="line">			//args---参数</span><br><span class="line">			//methodProxy---方法的代理对象</span><br><span class="line">			//不能直接使用 method.invoke，因为会再调用invoke导致死锁stackOverFlow</span><br><span class="line">			doBefore();</span><br><span class="line">			//使用父类方法，也就是原类方法获取返回值</span><br><span class="line">			Object result = methodProxy.invokeSuper(proxy, args);</span><br><span class="line">			System.out.println(<span class="string">"invoke super result..."</span>+result);</span><br><span class="line">			doAfter();</span><br><span class="line">			<span class="built_in">return</span> result;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line">	static &lt;T&gt; T getInstance(Class&lt;T&gt; clazz) &#123;</span><br><span class="line">		//第一个T泛型方法</span><br><span class="line">		Enhancer enhancer = new Enhancer();</span><br><span class="line">		enhancer.setSuperclass(clazz);</span><br><span class="line">		enhancer.setCallback(new BAInterceptor());</span><br><span class="line">		<span class="built_in">return</span> (T) enhancer.create();</span><br><span class="line">	&#125;</span><br><span class="line">	public static void main(String[] args) &#123;</span><br><span class="line">		Test <span class="built_in">test</span> = getInstance(Test.class);</span><br><span class="line">		test.hashCode();</span><br><span class="line">		test.finalMethod();</span><br><span class="line">		test.method();</span><br><span class="line">		test.staticMethod();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="请移步"><a href="#请移步" class="headerlink" title="请移步"></a>请移步</h3><p>个人主页: <a href="http://yangyitao.top" target="_blank" rel="noopener">yangyitao.top</a></p>

      
    </div>
    
  </div>
  
    
<nav id="article-nav">
  
    <a href="/blog/2019/04/12/字符串常量池在1.6与1.8以及String、StringBuffer、StringBuilder/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">&lt;</strong>
      <div class="article-nav-title">
        
          字符串常量池在1.6与1.8以及String、StringBuffer、StringBuilder
        
      </div>
    </a>
  
  
    <a href="/blog/2019/04/03/手撕B树/" id="article-nav-older" class="article-nav-link-wrap">
      <div class="article-nav-title">手撕B树</div>
      <strong class="article-nav-caption">&gt;</strong>
    </a>
  
</nav>

  
</article>


<div class="ds-share share" data-thread-key="动态代理与静态代理" data-title="动态代理与静态代理" data-url="http://eetal.gitee.io/blog/blog/2019/04/07/动态代理与静态代理/"  data-images="/blog/images/head.jpg" data-content="动态代理与静态代理">
    <div class="ds-share-inline">
      <ul  class="ds-share-icons-16">
      	<li data-toggle="ds-share-icons-more"><a class="ds-more" href="javascript:void(0);">分享到：</a></li>
        <li><a class="ds-weibo" href="javascript:void(0);" data-service="weibo">微博</a></li>
        <li><a class="ds-qzone" href="javascript:void(0);" data-service="qzone">QQ空间</a></li>
        <li><a class="ds-qqt" href="javascript:void(0);" data-service="qqt">腾讯微博</a></li>
        <li><a class="ds-wechat" href="javascript:void(0);" data-service="wechat">微信</a></li>
      </ul>
      <div class="ds-share-icons-more">
      </div>
    </div>
 </div>
 





</div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info">
      <div class="footer-left">
        &copy; 2019 Eetal
      </div>
        <div class="footer-right">
          <a href="http://hexo.io/" target="_blank">Hexo</a>  Theme <a href="https://github.com/smackgg/hexo-theme-smackdown" target="_blank">Smackdown</a>
        </div>
    </div>
  </div>
</footer>
    </div>
    
  <link rel="stylesheet" href="/blog/fancybox/jquery.fancybox.css">


<script>
	var yiliaConfig = {
		fancybox: true,
		mathjax: true,
		animate: true,
		isHome: false,
		isPost: true,
		isArchive: false,
		isTag: false,
		isCategory: false,
		open_in_new: false
	}
</script>
<script src="/blog/js/main.js"></script>



<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script src="//cdn.bootcss.com/mathjax/2.7.0/MathJax.js"></script>


  </div>
</body>
</html>